import * as React from 'react';
import { Menu, Icon, Spin, Dropdown, Avatar, Divider } from 'antd';
import { Link } from 'react-router-dom';
import Debounce from 'lodash-decorators/debounce';
import './header.less';

interface HeaderProps {
  userinfo: any;
  collapsed: any;
  onCollapse: (val: boolean) => void;
  isMobile: boolean;
  logo: string;
  onMenuClick: () => void;
}

export default class Header extends React.PureComponent<HeaderProps> {
  componentWillUnmount() {
    (this.triggerResizeEvent as any).cancel();
  }

  toggle = () => {
    const { collapsed, onCollapse } = this.props;
    onCollapse(!collapsed);
    this.triggerResizeEvent();
  };

  @Debounce(600)
  triggerResizeEvent() {
    const event = document.createEvent('HTMLEvents');
    event.initEvent('resize', true, false);
    window.dispatchEvent(event);
  }
  render() {
    const { userinfo, collapsed, isMobile, logo, onMenuClick } = this.props;
    const menu = (
      <Menu className="menu" selectedKeys={[]} onClick={onMenuClick}>
        <Menu.Item key="logout">
          <Icon type="logout" />退出登录
        </Menu.Item>
      </Menu>
    );

    return (
      <div className="header">
        {isMobile && [
          <Link to="/" className="logo" key="logo">
            <img src={logo} alt="logo" width="32" />
          </Link>,
          <Divider type="vertical" key="line" />,
        ]}
        <Icon
          className="trigger"
          type={collapsed ? 'menu-unfold' : 'menu-fold'}
          onClick={this.toggle}
        />
        <div className="right">
          {userinfo ? (
            <Dropdown overlay={menu}>
              <span className="action account">
                <Icon type="user" />
                <span className="name">{userinfo.name}</span>
              </span>
            </Dropdown>
          ) : (
            <Spin size="small" style={{ marginLeft: 8 }} />
          )}
        </div>
      </div>
    );
  }
}
